<template>
	<el-dialog :title="title" width="500px" :visible.sync="dialogVisible">
		<el-form ref="form" :rules="rules" :model="form" label-width="80px">
			<el-form-item label="分类名称" prop="name">
				<el-input v-model="form.name" clearable></el-input>
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button size="small" @click="dialogVisible = false">取 消</el-button>
			<el-button size="small" type="primary" @click="submit">确 定</el-button>
		</div>
	</el-dialog>
</template>

<script>
import { insertCategory, updateCategory } from '@/api/info'
export default {
	props: ['editItem'],
	data() {
		return {
			dialogVisible: false,
			form: {
				name: '',
			},
			rules:{
				name: [{
					required: true,
					message: '请输入分类名称',
					trigger: 'blur'
				}],
			}
		}
	},
	watch: {
		dialogVisible(val) {
			if (val) {
				if (Object.values(this.editItem).length != 0) {
					for (const key in this.form) {
						this.form[key] = this.editItem[key]
					}
				} else {
					this.form = {
						name: ''
					}
				}
			}else{
				this.$refs['form'].resetFields()
			}
		}
	},
	methods: {
		submit() {
			this.$refs['form'].validate((valid) => {
				if (valid) {
					if (Object.values(this.editItem).length != 0) {
						// 编辑
						let params={
							id:this.editItem.id,
							name:this.form.name
						}
						updateCategory(params).then(res => {
							this.dialogVisible = false
							this.form.name=''
							this.$emit('getList')
						})
					} else {
						insertCategory({...this.form}).then(res => {
							this.dialogVisible = false
							this.form.name=''
							this.$emit('getList')
						})
					}
				} else {
					this.$message({
						message: '请检查表单错误',
						type: 'error'
					})
					return false
				}
			})
		}
	}
}
</script>

<style></style>
